<template>
  <div class="user-management">
    <div class="page-header">
      <h2>User Management</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>Add User
      </el-button>
    </div>

    <!-- Search Bar -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="Username">
          <el-input
              v-model="searchForm.username"
              placeholder="Enter Username"
              clearable
              @keyup.enter="handleSearch"
              style="width: 220px;"
          />
        </el-form-item>
        <el-form-item label="Role">
          <el-select
              v-model="searchForm.role"
              placeholder="Select Role"
              clearable
              style="width: 220px;"
              popper-class="wider-select-dropdown"
          >
            <el-option
                v-for="role in roles"
                :key="role.name"
                :label="role.name"
                :value="role.name"
            >
              <span class="option-label">{{ role.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="Status">
          <el-select
              v-model="searchForm.status"
              placeholder="Select Status"
              clearable
              style="width: 220px;"
              popper-class="wider-select-dropdown"
          >
            <el-option label="Active" value="active">
              <div class="status-option">
                <el-tag type="success" size="small">Active</el-tag>
                <span class="option-label">Active</span>
              </div>
            </el-option>
            <el-option label="Inactive" value="inactive">
              <div class="status-option">
                <el-tag type="danger" size="small">Inactive</el-tag>
                <span class="option-label">Inactive</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" size="default">
            <el-icon><Search /></el-icon>Search
          </el-button>
          <el-button @click="handleReset" size="default">
            <el-icon><Refresh /></el-icon>Reset
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- User List -->
    <el-card class="list-card">
      <el-table
          v-loading="loading"
          :data="userList"
          border
          stripe
          style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="Username" width="120" />
        <el-table-column prop="realName" label="Real Name" width="120" />
        <el-table-column prop="nickname" label="Nickname" width="120" />
        <el-table-column prop="email" label="Email" width="180" />
        <el-table-column prop="phone" label="Phone" width="120" />
        <el-table-column label="Role" width="150">
          <template #default="{ row }">
            <el-tag
                v-for="role in row.roles"
                :key="role"
                :type="role === 'ADMIN' ? 'danger' : 'success'"
                class="role-tag"
            >
              {{ role }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="Status" width="100">
          <template #default="{ row }">
            <el-tag
                :type="row.status === 'active' ? 'success' : 'danger'"
            >
              {{ row.status === 'active' ? 'Active' : 'Inactive' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="Create Time" width="180" />
        <el-table-column label="Actions" fixed="right" width="200">
          <template #default="{ row }">
            <el-button
                type="primary"
                link
                @click="handleEdit(row)"
            >
              Edit
            </el-button>
            <el-button
                type="primary"
                link
                @click="handleResetPassword(row)"
            >
              Reset Password
            </el-button>
            <el-button
                :type="row.status === 'active' ? 'danger' : 'success'"
                link
                @click="handleToggleStatus(row)"
            >
              {{ row.status === 'active' ? 'Disable' : 'Enable' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- Pagination -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- User Form Dialog -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="500px"
    >
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
      >
        <el-form-item
            label="Username"
            prop="username"
            v-if="dialogType === 'add'"
        >
          <el-input
              v-model="form.username"
              placeholder="Enter Username"
          />
        </el-form-item>
        <el-form-item
            label="Password"
            prop="password"
            v-if="dialogType === 'add'"
        >
          <el-input
              v-model="form.password"
              type="password"
              placeholder="Enter Password"
              show-password
          />
        </el-form-item>
        <el-form-item label="Real Name" prop="realName">
          <el-input
              v-model="form.realName"
              placeholder="Enter Real Name"
          />
        </el-form-item>
        <el-form-item label="Nickname" prop="nickname">
          <el-input
              v-model="form.nickname"
              placeholder="Enter Nickname"
          />
        </el-form-item>
        <el-form-item label="Email" prop="email">
          <el-input
              v-model="form.email"
              placeholder="Enter Email"
          />
        </el-form-item>
        <el-form-item label="Phone" prop="phone">
          <el-input
              v-model="form.phone"
              placeholder="Enter Phone Number"
          />
        </el-form-item>
        <el-form-item label="Role" prop="roles">
          <el-select
              v-model="form.roles"
              placeholder="Select Role"
          >
            <el-option
                v-for="role in roles"
                :key="role.name"
                :label="role.name"
                :value="role.name"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">Cancel</el-button>
          <el-button
              type="primary"
              @click="handleSubmit"
              :loading="submitLoading"
          >
            Confirm
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- Reset Password Dialog -->
    <el-dialog
        title="Reset Password"
        v-model="resetPasswordVisible"
        width="400px"
    >
      <el-form
          ref="resetPasswordFormRef"
          :model="resetPasswordForm"
          :rules="resetPasswordRules"
          label-width="100px"
      >
        <el-form-item label="New Password" prop="password">
          <el-input
              v-model="resetPasswordForm.password"
              type="password"
              placeholder="Enter New Password"
              show-password
          />
        </el-form-item>
        <el-form-item label="Confirm Password" prop="confirmPassword">
          <el-input
              v-model="resetPasswordForm.confirmPassword"
              type="password"
              placeholder="Enter New Password Again"
              show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetPasswordVisible = false">Cancel</el-button>
          <el-button
              type="primary"
              @click="handleResetPasswordSubmit"
              :loading="resetPasswordLoading"
          >
            Confirm
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>


<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import {
  Plus,
  Search,
  Refresh
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import type {
  UserProfile,
  Role,
  CreateUserRequest,
  UpdateUserRequest
} from '../../types/user'
import axios from '../../utils/axios'
import { useUserStore } from '../../stores/user'

// State
const loading = ref(false)
const submitLoading = ref(false)
const resetPasswordLoading = ref(false)
const dialogVisible = ref(false)
const resetPasswordVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const userList = ref<UserProfile[]>([])
const roles = ref<Role[]>([])

// Form
const formRef = ref<FormInstance>()
const resetPasswordFormRef = ref<FormInstance>()

const searchForm = reactive({
  username: '',
  role: '',
  status: ''
})

const form = reactive<Omit<CreateUserRequest & UpdateUserRequest, 'roles'> & { roles: string | string[] }>({
  username: '',
  password: '',
  realName: '',
  nickname: '',
  email: '',
  phone: '',
  roles: ''
})

const resetPasswordForm = reactive({
  userId: 0,
  password: '',
  confirmPassword: ''
})

// Computed properties
const dialogTitle = computed(() => {
  return dialogType.value === 'add' ? 'Add User' : 'Edit User'
})

// Form validation rules
const rules = {
  username: [
    { required: true, message: 'Please enter the username', trigger: 'blur' },
    { min: 4, max: 20, message: 'Length must be between 4 and 20 characters', trigger: 'blur' }
  ],
  password: [
    { required: true, message: 'Please enter the password', trigger: 'blur' },
    { min: 6, message: 'Password length cannot be less than 6 characters', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: 'Please enter the real name', trigger: 'blur' },
    { min: 2, max: 20, message: 'Length must be between 2 and 20 characters', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: 'Please enter the nickname', trigger: 'blur' },
    { min: 2, max: 20, message: 'Length must be between 2 and 20 characters', trigger: 'blur' }
  ],
  email: [
    { required: true, message: 'Please enter the email', trigger: 'blur' },
    { type: 'email', message: 'Please enter a valid email address', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: 'Please enter the phone number', trigger: 'blur' },
    { pattern: /^[0-9]{10,15}$/, message: 'Please enter a valid phone number', trigger: 'blur' }
  ],
  roles: [
    { required: true, message: 'Please select a role', trigger: 'change' }
  ]
}

const resetPasswordRules = {
  password: [
    { required: true, message: 'Please enter a new password', trigger: 'blur' },
    { min: 6, message: 'Password length cannot be less than 6 characters', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: 'Please enter the new password again', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== resetPasswordForm.password) {
          callback(new Error('The two passwords entered do not match'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// Methods
const fetchUserList = async () => {
  loading.value = true
  try {
    // Ensure token exists
    const token = localStorage.getItem('token');
    const headers = token ? { Authorization: `Bearer ${token}` } : {};
    
    const response = await axios.get('/api/admin/users', {
      params: {
        page: currentPage.value,
        size: pageSize.value,
        ...searchForm
      },
      headers
    })
    userList.value = response.data.content
    total.value = response.data.total
  } catch (error: any) {
    console.error('Fetch user list error:', error);
    ElMessage.error(error.response?.data?.message || 'Failed to retrieve user list')
  } finally {
    loading.value = false
  }
}

const fetchRoles = async () => {
  try {
    // Ensure token exists
    const token = localStorage.getItem('token');
    const headers = token ? { Authorization: `Bearer ${token}` } : {};
    
    const response = await axios.get('/api/admin/roles', { headers })
    roles.value = response.data
  } catch (error: any) {
    console.error('Fetch roles error:', error);
    ElMessage.error(error.response?.data?.message || 'Failed to retrieve role list')
  }
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.username = ''
  form.password = ''
  form.realName = ''
  form.nickname = ''
  form.email = ''
  form.phone = ''
  form.roles = ''
}

const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row: UserProfile) => {
  dialogType.value = 'edit'
  const userData = { ...row };

  // Ensure only the first role is selected
  if (userData.roles && userData.roles.length > 0) {
    userData.roles = userData.roles[0];
  } else {
    userData.roles = '';
  }

  Object.assign(form, userData);
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        // Create a copy of the form data
        const formData = { ...form };

        // Convert the single role value to an array
        if (formData.roles && typeof formData.roles === 'string') {
          formData.roles = [formData.roles];
        } else if (!formData.roles) {
          formData.roles = [];
        }

        // Ensure token exists
        const token = localStorage.getItem('token');
        const headers = token ? { Authorization: `Bearer ${token}` } : {};

        if (dialogType.value === 'add') {
          await axios.post('/api/admin/users', formData, { headers })
          ElMessage.success('Successfully added user')
        } else {
          await axios.put(`/api/admin/users/${formData.id}`, formData, { headers })
          ElMessage.success('Successfully edited user')
        }
        dialogVisible.value = false
        fetchUserList()
      } catch (error: any) {
        console.error('Error details:', error);
        ElMessage.error(
            error.response?.data?.message ||
            (dialogType.value === 'add' ? 'Failed to add user' : 'Failed to edit user')
        )
      } finally {
        submitLoading.value = false
      }
    }
  })
}

const handleResetPassword = (row: UserProfile) => {
  resetPasswordForm.userId = row.id
  resetPasswordForm.password = ''
  resetPasswordForm.confirmPassword = ''
  resetPasswordVisible.value = true
}

const handleResetPasswordSubmit = async () => {
  if (!resetPasswordFormRef.value) return

  await resetPasswordFormRef.value.validate(async (valid) => {
    if (valid) {
      resetPasswordLoading.value = true
      try {
        // Ensure token exists
        const token = localStorage.getItem('token');
        const headers = token ? { Authorization: `Bearer ${token}` } : {};
        
        await axios.post(`/api/admin/users/${resetPasswordForm.userId}/reset-password`, {
          password: resetPasswordForm.password
        }, { headers })
        
        ElMessage.success('Successfully reset password')
        resetPasswordVisible.value = false
      } catch (error: any) {
        console.error('Reset password error:', error);
        ElMessage.error(error.response?.data?.message || 'Failed to reset password')
      } finally {
        resetPasswordLoading.value = false
      }
    }
  })
}

const handleToggleStatus = async (row: UserProfile) => {
  try {
    const action = row.status === 'active' ? 'disable' : 'enable'
    await ElMessageBox.confirm(
        `Are you sure you want to ${action} this user?`,
        'Hint',
        {
          confirmButtonText: 'Confirm',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }
    )

    // Ensure token exists
    const token = localStorage.getItem('token');
    const headers = token ? { Authorization: `Bearer ${token}` } : {};
    
    await axios.post(`/api/admin/users/${row.id}/toggle-status`, {}, { headers })
    ElMessage.success(`Successfully ${action}d user`)
    fetchUserList()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('Toggle status error:', error);
      ElMessage.error(error.response?.data?.message || 'Operation failed')
    }
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchUserList()
}

const handleReset = () => {
  searchForm.username = ''
  searchForm.role = ''
  searchForm.status = ''
  handleSearch()
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchUserList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchUserList()
}

// Lifecycle hooks
onMounted(async () => {
  console.log('===== UserManagement component mounted =====')

  // Debugging: Check user login and permission status
  const token = localStorage.getItem('token')
  console.log('Current token existence status:', !!token)
  if (token) {
    console.log('First 10 characters of Token:', token.substring(0, 10) + '...')
  }

  // Check user store state
  const userStore = useUserStore()
  console.log('User login status:', userStore.isLoggedIn)
  console.log('User admin status:', userStore.isAdmin)
  console.log('User roles:', userStore.user.roles)

  // Add check items before request
  console.log('Starting to request user list and role data')

  try {
    // Separate requests to more clearly show which requests succeeded or failed
    await fetchUserList()
    console.log('Successfully requested user list')

    await fetchRoles()
    console.log('Successfully requested role list')
  } catch (error) {
    console.error('Failed to request data:', error)
  }
})
</script>
<style scoped>
.user-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.list-card {
  margin-bottom: 20px;
}

.role-tag {
  margin-right: 5px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-dialog__body) {
  padding-top: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* Search area enhanced styles */
.search-card :deep(.el-form--inline .el-form-item) {
  margin-right: 20px;
  margin-bottom: 16px;
}

.search-card :deep(.el-input__wrapper),
.search-card :deep(.el-select .el-input__wrapper) {
  height: 40px;
}

.search-card :deep(.el-select) {
  width: 100%;
}

.search-card :deep(.el-input__inner) {
  font-size: 14px;
}

.search-card :deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
}

/* Dropdown selector style adjustments */
:deep(.wider-select-dropdown) {
  min-width: 220px !important; 
}

:deep(.el-select-dropdown__item) {
  height: auto;
  line-height: 34px;
  padding: 8px 12px;
}

.status-option {
  display: flex;
  align-items: center;
  padding: 2px 0;
}

.status-option .el-tag {
  width: 70px;
  text-align: center;
}

.option-label {
  margin-left: 8px;
  font-size: 14px;
}
</style> 